<?php

namespace HelpDesk\Users\Dao;

use \HelpDesk\Users\Model\User;
use \PDO;

class UserSqlDao implements IUserDao {

    private $db;

    public function get($id) {
        $namesQuery = $this->db->prepare("SELECT * FROM USERS WHERE ID = :id");
        $namesQuery->bindValue(':id', $id, PDO::PARAM_INT);
        $namesQuery->execute();
        $row = $namesQuery->fetch(PDO::FETCH_NUM);

        if ($row === false) {
            return null;
        }

        return $this->createUser($row);
    }

    public function getByLogin($login) {
        $namesQuery = $this->db->prepare("SELECT * FROM USERS WHERE LOGIN = :login");
        $namesQuery->bindValue(':login', $login, PDO::PARAM_STR);
        $namesQuery->execute();
        $row = $namesQuery->fetch(PDO::FETCH_NUM);

        if (is_null($row)) {
            return null;
        }

        return $this->createUser($row);
    }

    public function getAll() {
        $namesQuery = $this->db->prepare("SELECT * FROM USERS");
        $namesQuery->execute();

        $result = array();
        while ($row = $namesQuery->fetch(PDO::FETCH_NUM)) {
            $result[] = $this->createUser($row);
        }
        return $result;
    }
    
    public function load($id) {
        $user = $this->get($id);
        if(is_null($user)) {
            throw new \Core\Dao\ObjectNotFoundException("User", $id);
        }
        
        return $user;
    }

    private function createUser($row) {
        $user = new User();
        $user->setId($row[0]);
        $user->setLogin($row[1]);
        $user->setFirstName($row[2]);
        $user->setSecondName($row[3]);
        return $user;
    }

    public function setDb($db) {
        $this->db = $db;
    }

}